<script lang="ts" setup>
import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  DeleteOutlined,
  DownloadOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
  SearchOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { delPictureUsingPost, getPictureVoByIdUsingGet } from '@/api/pictureController'
import { useLoginUserStore } from '@/stores/UseLoginUserStore'
import dayjs from 'dayjs'
import { createVNode } from 'vue'
import {toHexColor} from "@/utils/format";

const router = useRouter()
const route = useRoute()
const loginUserStore = useLoginUserStore()

// 图片数据
const picture = ref<API.PictureVO>({})
const loading = ref(false)

// 格式化文件大小
const formatSize = (size?: number) => {
  if (!size) return '未知'
  const units = ['B', 'KB', 'MB', 'GB']
  let unitIndex = 0
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024
    unitIndex++
  }
  return `${size.toFixed(2)} ${units[unitIndex]}`
}

// 获取图片详情
const getPictureById = async () => {
  try {
    loading.value = true
    const res = await getPictureVoByIdUsingGet({
      id: route.params.id as string
    })
    if (res.data.code === 0 && res.data.data) {
      picture.value = res.data.data
    } else {
      message.error('获取详情失败: ' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取失败: ' + e.message)
  } finally {
    loading.value = false
  }
}

// 权限判断
const canEdit = computed(() => {
  const user = picture.value.user || {}
  return loginUserStore.loginUser?.id === user.id || loginUserStore.loginUser?.userRole === 'admin'
})

// 编辑操作
const doEdit = () => {
  router.push(`/add_picture?id=${picture.value.id}`)
}

// 删除操作
const doDelete = () => {
  Modal.confirm({
    title: '确认删除图片？',
    icon: createVNode(ExclamationCircleOutlined),
    content: '删除后将无法恢复，请谨慎操作！',
    okText: '确认删除',
    okType: 'danger',
    cancelText: '取消',
    async onOk() {
      try {
        const res = await delPictureUsingPost({ id: picture.value.id })
        if (res.data.code === 0) {
          message.success('删除成功')
          router.push('/home')
        }
      } catch (e: any) {
        message.error('删除失败: ' + e.message)
      }
    }
  })
}
// 搜索
const doSearch = () => {
  window.open(`/search_picture?pictureId=${route.params.id}`)
}

// 下载图片
const doDownload = () => {
  if (picture.value.url) {
    const link = document.createElement('a')
    link.href = picture.value.url
    link.download = picture.value.name || '未命名图片'
    link.style.display = 'none'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}
const previewVisible = ref(false);
const currentPreviewUrl = ref('');
onMounted(() => {
  getPictureById()
})
const showPreview = (url: string) => {
  currentPreviewUrl.value = url;
  previewVisible.value = true;
};
</script>

<template>
  <div class="picture-detail">
    <!-- 图片预览模态框 -->
    <Modal
        :visible="previewVisible"
        :footer="null"
        @cancel="previewVisible = false"
        :style="{ width: '80vw', height: '80vh' }"
    centered
    >
    <img :src="currentPreviewUrl" class="preview-modal-image" style="width:100%; height:100%; object-fit:contain;" />  <!-- 确保图片适应容器 -->
    </Modal>
    <a-spin :spinning="loading">
      <a-row :gutter="24">
        <!-- 图片预览区域 -->
        <a-col :xs="24" :md="16" :lg="18">
          <a-card
              class="preview-card"
              :bordered="false"
              :head-style="{ border: 'none', padding: '0 24px' }"
          >
            <template #title>
              <span class="card-title">图片预览</span>
            </template>

            <div class="image-container">
              <a-image
                  :src="picture.url"
                  :preview="{ visible: false }"
                  class="detail-image"
                  @click="showPreview(picture.url)"
              >
                <template #placeholder>
                  <div class="image-placeholder">
                    <a-spin size="large" />
                  </div>
                </template>
              </a-image>
            </div>
          </a-card>
        </a-col>

        <!-- 信息展示区域 -->
        <a-col :xs="24" :md="8" :lg="6">
          <a-card
              class="info-card"
              :bordered="false"
              :head-style="{ border: 'none', padding: '0 24px' }"
          >
            <template #title>
              <span class="card-title">图片信息</span>
            </template>

            <a-descriptions :column="1" class="info-list">
              <a-descriptions-item label="作者">
                <a-space>
                  <a-avatar :src="picture.user?.userAvatar" />
                  <span class="author-name">{{ picture.user?.userName || '匿名用户' }}</span>
                </a-space>
              </a-descriptions-item>

              <a-descriptions-item label="名称">{{ picture.name || '未命名' }}</a-descriptions-item>
              <a-descriptions-item label="简介">{{ picture.introduction || '暂无简介' }}</a-descriptions-item>

              <a-descriptions-item label="分类">
                <a-tag color="blue">{{ picture.category || '默认分类' }}</a-tag>
              </a-descriptions-item>

              <a-descriptions-item label="标签">
                <a-space wrap v-if="picture.tags?.length">
                  <a-tag
                      v-for="tag in picture.tags"
                      :key="tag"
                      color="orange"
                  >
                    {{ tag }}
                  </a-tag>
                </a-space>
                <span v-else class="empty-text">暂无标签</span>
              </a-descriptions-item>

              <a-divider class="info-divider" />

              <a-descriptions-item label="尺寸">
                {{ picture.picWidth }} × {{ picture.picHeight }} px
              </a-descriptions-item>

              <a-descriptions-item label="文件大小">
                {{ formatSize(picture.picSize) }}
              </a-descriptions-item>

              <a-descriptions-item label="上传时间">
                {{ dayjs(picture.createTime).format('YYYY-MM-DD HH:mm') }}
              </a-descriptions-item>
              <a-descriptions-item label="主色调">
                <a-space>
                  {{ picture.picColor ?? '-' }}
                  <div
                      v-if="picture.picColor"
                      :style="{
        backgroundColor: toHexColor(picture.picColor),
        width: '16px',
        height: '16px',
      }"
                  />
                </a-space>
              </a-descriptions-item>

            </a-descriptions>
          </a-card>
        </a-col>
      </a-row>

      <!-- 操作按钮组 -->
      <div class="action-group">
        <a-tooltip title="下载原图">
          <a-button
              type="primary"
              shape="circle"
              size="large"
              class="action-btn download-btn"
              @click="doDownload"
          >
            <template #icon><DownloadOutlined /></template>
          </a-button>
        </a-tooltip>

        <a-tooltip v-if="canEdit" title="编辑信息">
          <a-button
              type="primary"
              shape="circle"
              size="large"
              class="action-btn edit-btn"
              @click="doEdit"
          >
            <template #icon><EditOutlined /></template>
          </a-button>
        </a-tooltip>

        <a-tooltip v-if="canEdit" title="删除图片">
          <a-button
              type="primary"
              shape="circle"
              size="large"
              class="action-btn delete-btn"
              @click="doDelete"
          >
            <template #icon><DeleteOutlined /></template>
          </a-button>
        </a-tooltip>
        <a-tooltip v-if="canEdit" title="搜索图片">
          <a-button
              type="primary"
              shape="circle"
              size="large"
              class="action-btn delete-btn"
              @click="doSearch"
          >
            <template #icon><SearchOutlined /></template>
          </a-button>
        </a-tooltip>
      </div>
    </a-spin>
  </div>
</template>

<style scoped lang="less">
.picture-detail {
  padding: 24px;
  min-height: 100vh;
  background: linear-gradient(to bottom right, #f8f9fa, #e9ecef);

  .card-title {
    font-size: 18px;
    font-weight: 600;
    color: #1a1a1a;
  }

  .preview-card {
    height: calc(100vh - 140px);
    border-radius: 12px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s;

    &:hover {
      transform: translateY(-2px);
    }

    :deep(.ant-card-body) {
      height: 100%;
      padding: 0;
      display: flex;
    }
  }

  .image-container {
    flex: 1;
    position: relative;
    width: 100%;
    background: #f8f9fa;

    .detail-image {
      width: 100%;
      height: 100%;
      object-fit: contain;

      :deep(.ant-image-img) {
        width: 100%;
        height: 100%;
        object-fit: contain;
      }
    }

    .image-placeholder {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(255, 255, 255, 0.8);
    }
  }

  .info-list {
    :deep(.ant-descriptions-item-label) {
      color: #666;
      font-weight: 500;
      min-width: 80px;
    }

    :deep(.ant-descriptions-item-content) {
      color: #333;
    }

    .author-name {
      font-weight: 500;
    }

    .empty-text {
      color: #999;
      font-style: italic;
    }

    .info-divider {
      margin: 16px 0;
    }
  }

  .action-group {
    position: fixed;
    right: 40px;
    bottom: 40px;
    display: flex;
    gap: 16px;
    z-index: 1000;

    .action-btn {
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      transition: all 0.3s;

      &:hover {
        transform: scale(1.1);
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
      }
    }

    .download-btn {
      background: #1890ff;
      border-color: #1890ff;
    }

    .edit-btn {
      background: #52c41a;
      border-color: #52c41a;
    }

    .delete-btn {
      background: #ff4d4f;
      border-color: #ff4d4f;
    }
  }
}

@media (max-width: 768px) {
  .picture-detail {
    padding: 12px;

    .preview-card {
      height: auto;
      min-height: 60vh;
    }

    .action-group {
      right: 16px;
      bottom: 16px;
      gap: 12px;

      .action-btn {
        width: 44px;
        height: 44px;
      }
    }
  }
}
</style>
